//
// Created by 45595 on 2021/10/5.
//

#include <bits/stdc++.h>

using namespace std;

const int MAXN = 100010;

struct node{
    int address,data,next;
    bool flag;
}nodes[MAXN];

bool cmp(node &a,node &b){
    if(a.flag==false || b.flag==false){
        return a.flag>b.flag;
    }else{
        return a.data<b.data;
    }
}

int main(){
    freopen("../A1052.txt", "r", stdin);
    for(int i=0;i<MAXN;i++){
        nodes[i].flag = false;
    }
    int N,Start;
    cin>>N>>Start;

    int address;
    for(int i=0;i<N;i++){
        cin>>address;
        nodes[address].address = address;
        cin>>nodes[address].data>>nodes[address].next;
    }
    int p=Start,count=0;
    while(p!=-1){
        nodes[p].flag = true;
        count++;
        p = nodes[p].next;
    }

    if(count==0){
        cout<<"0 -1"<<endl;
    }else{
        sort(nodes,nodes+MAXN,cmp);
        printf("%d %05d\n",count,nodes[0].address);
        for(int i=0;i<count-1;i++){
            printf("%05d %d %05d\n",nodes[i].address,nodes[i].data,nodes[i+1].address);
        }
        printf("%05d %d -1\n",nodes[count-1].address,nodes[count-1].data);
    }

    return 0;
}